package com.service.screenWeb.controller;


import com.alibaba.fastjson.JSONArray;
import com.service.config.utils.*;
import com.service.screenWeb.dto.*;
import com.service.screenWeb.entity.*;
import com.service.screenWeb.service.ProgrammeInfoService;
import com.service.screenWeb.service.ScreenUserService;
import com.service.screenWeb.service.UserServiceInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.el.lang.ELArithmetic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.service.config.constant.Constant.*;
import org.apache.commons.lang.StringEscapeUtils;
/**
 * 大屏用户表(ScreenUser)表控制层
 *
 * @author makejava
 * @since 2021-03-29 15:32:44
 */
@RestController
@RequestMapping("screenUser")
@Api(value = "大屏用户信息管理",description = "大屏用户信息管理")
public class ScreenUserController {
    /**
     * 服务对象
     */
    @Resource
    private ScreenUserService screenUserService;

    @Autowired
    private RedisUtil redisUtil;
    @Resource
    private UserServiceInfoService userServiceInfoService;
    @Resource
    private ProgrammeInfoService programmeInfoService;
    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public ScreenUser selectOne(String id) {
        return this.screenUserService.queryById(id);
    }




//    @PostMapping("disposeUserModel")
//    @ApiOperation(value = "配置用户模板和组件")
//    @ResponseBody
//    public Result disposeUserModel(@RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken,
//                                   @RequestBody UserServiceInfoDto userServiceInfoDto) throws Exception {
//
//        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
//            String userId = UserTokenManager.getUserId(cloudAuthToken);
//            if (redisUtil.exist(cloudAuthToken + userId)) {
//                UserServiceInfo userServiceInfo = ModelMapperUtil.strictMap(userServiceInfoDto, UserServiceInfo.class);
//                userServiceInfo.setUserId(userId);
//                List<AssemblyDto> assemblyInfo = userServiceInfoDto.getAssemblyInfo();
//                userServiceInfo.setAssemblyInfo(JsonXMLUtils.obj2json(assemblyInfo));
//                userServiceInfoService.update(userServiceInfo);
//                return Result.ok();
//            }else {
//                return Result.failure(USERNAME_Off_SITE, usernameOffSite);
//            }
//        }
//        return Result.failure(USER_NOT_LOGIN, "用户未登录");
//    }
    @PostMapping("addProgramme")
    @ApiOperation(value = "新增方案")
    @ResponseBody
    public Result addProgramme(@RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken,
                                   @RequestBody ProgrammeInfoDto programmeInfoDto) throws Exception {

        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                ProgrammeInfo programmeInfo = ModelMapperUtil.strictMap(programmeInfoDto, ProgrammeInfo.class);
                programmeInfo.setUserId(userId);
                List<ProgrammeInfoViewDto> programmeInfoViewList = programmeInfoDto.getProgrammeInfoViewList();
                programmeInfo.setLayoutInfo(JsonXMLUtils.obj2json(programmeInfoViewList));
                programmeInfoService.insert(programmeInfo);
                return Result.ok();
            }else {
                return Result.failure(USERNAME_Off_SITE, usernameOffSite);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }
    @PostMapping("updateProgramme")
    @ApiOperation(value = "更新方案")
    @ResponseBody
    public Result updateProgramme(@RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken,
                               @RequestBody ProgrammeInfoDto programmeInfoDto) throws Exception {

        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                ProgrammeInfo programmeInfo = ModelMapperUtil.strictMap(programmeInfoDto, ProgrammeInfo.class);
                programmeInfo.setUserId(userId);
                List<ProgrammeInfoViewDto> programmeInfoViewList = programmeInfoDto.getProgrammeInfoViewList();
                List<ProgrammeInfoViewDto> collect = programmeInfoViewList.stream().filter(programmeInfoViewDto -> programmeInfoViewDto.getAssemblyConfigureId() == null ||
                        programmeInfoViewDto.getLayoutId() == null).collect(Collectors.toList());
                if (collect.size()>0) {
                    return Result.failure(10015,"参数传输错误，请校验参数");
                }
                programmeInfo.setLayoutInfo(JsonXMLUtils.obj2json(programmeInfoViewList));
                programmeInfoService.update(programmeInfo);
                return Result.ok();
            }else {
                return Result.failure(USERNAME_Off_SITE, usernameOffSite);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    @PostMapping("checkApiAccount")
    @ApiOperation(value = "校验云管平台的账号和密码")
    @ResponseBody
    public Result checkTenant(@RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken,
                              @RequestBody CheckTenantDto checkTenantDto) {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                Map  check = screenUserService.check(checkTenantDto, userId);
                if (check.containsKey("errorMsg")) {
                    return Result.ok().setData(check);
                }
                return Result.ok();
            }else {
                return Result.failure(USERNAME_Off_SITE, usernameOffSite);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    @PostMapping("addApiAccount")
    @ApiOperation(value = "增加云管api账号和密码")
    @ResponseBody
    public Result addApiAccount(@RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken,
                             @RequestBody TenantDto tenantDto) throws Exception {

        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                List<ScreenUser> screenUserList = screenUserService.insertOrUpdate(ModelMapperUtil.strictMap(tenantDto, ScreenUser.class), userId);
                if (screenUserList != null) {
                    return Result.failure(CLOUD_CAMPUS_ACCOUNT_SAME, "云管理账号同域名已存在，是否覆盖");
                }
                return Result.ok();
            }else {
                return Result.failure(USERNAME_Off_SITE, usernameOffSite);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }
    @PostMapping("updateApiAccount")
    @ApiOperation(value = "更新云管的密码")
    @ResponseBody
    public Result updateApiAccount(@RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken,
                                @RequestBody TenantDto tenantDto) {

        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                screenUserService.updateApiAccount(ModelMapperUtil.strictMap(tenantDto,ScreenUser.class));
                return Result.ok();
            }else {
                return Result.failure(USERNAME_Off_SITE, usernameOffSite);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }
    @GetMapping("deleteApiAccount")
    @ApiOperation(value = "删除云管理api账号")
    @ResponseBody
    public Result deleteApiAccount(@RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken,
                                   @RequestParam("screen_id") @ApiParam("api账号id") String screen_id) {

        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                screenUserService.deleteById(screen_id);
                return Result.ok();
            }else {
                return Result.failure(USERNAME_Off_SITE, usernameOffSite);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }
    @GetMapping("enableAndDisable")
    @ApiOperation(value = "api账号的启用和禁用")
    @ResponseBody
    public Result enableAndDisable(@RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken,
                                   @RequestParam("screen_user_id") @ApiParam("大屏用户id") String screen_user_id,
                                   @ApiParam("状态：true-启用，false-禁用")@RequestParam("status") Boolean status,
                                   @ApiParam("域名")@RequestParam("domain") String domain) {

        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                screenUserService.serviceStatusBind(screen_user_id,status,userId,domain);
                return Result.ok();
            }else {
                return Result.failure(USERNAME_Off_SITE, usernameOffSite);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }
    @GetMapping("findAllApi")
    @ApiOperation(value = "云管账号列表")
    @ResponseBody
    public Result findAllApi(@RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                List<ScreenUserDto> screenUserList = screenUserService.queryAll(userId);
                return Result.ok().setData(screenUserList);
            }else {
                return Result.failure(USERNAME_Off_SITE, usernameOffSite);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }
}
